package com.xcc.produce;

import com.xcc.bean.DataIn;
import com.xcc.bean.DataOut;
import com.xcc.bean.Producer;
import com.xcc.util.DateUtil;
import com.xcc.util.NumberUtil;
import jdk.nashorn.internal.ir.Flags;

import java.io.IOException;
import java.util.List;
import java.util.Random;

public class MyProducer implements Producer {

    private DataIn in;
    private DataOut out;
    //控制生产的开关
    private volatile boolean flag = true;

    public void setDataIn(DataIn in) {
        this.in = in;
    }

    public void setDataOut(DataOut out) {
        this.out = out;
    }

    public void produce() {
        //加载所有的数据
        List<Contact> contacts = in.read(Contact.class);
        try {
            while (flag) {
                int index1 = new Random().nextInt(contacts.size());
                int index2;
                while (true) {
                    index2 = new Random().nextInt(contacts.size());
                    if (index1 != index2) {
                        break;
                    }
                }

                //获取开始时间
                String startTime = "20190101000000";
                String endTime = "20191231235959";
                long start = DateUtil.parse(startTime, "yyyyMMddHHmmss").getTime();
                long end = DateUtil.parse(endTime, "yyyyMMddHHmmss").getTime();
                long current = start + (long) (Math.random() * (end - start));
                String currentTime = DateUtil.format(current,"yyyyMMddHHmmss");

                //获取通话时长
                String duration = NumberUtil.format(new Random().nextInt(3000), 4);
                Call call = new Call(contacts.get(index1).getTel(), contacts.get(index2).getTel(), currentTime, duration);
                System.out.println(call);
                out.write(call.toString());

                Thread.sleep(500);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void flagClose() {
        this.flag = false;
    }

    public void close() throws IOException {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }


    public static void main(String[] args) {
        MyProducer producer = new MyProducer();
        System.out.println(producer.flag);
        producer.flagClose();
        System.out.println(producer.flag);



    }
}
